package au.com.bus4u.service.impl;

import au.com.bus4u.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service("emailService")
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.profiles.serverUrl}")
    private String serverUrl;

    @Autowired
    private JavaMailSender mailSender;

    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    /**
     * 发送用户注册的效验邮件
     * 内容格式：http://localhost:8080/validationUserEmail/user_id
     * @param user_id
     * @param user_email
     * @throws Exception
     */
    @Override
    public void sendUserRegistValidationEmail(String user_id, String user_email){
        String subject = "主题：bus4u新用户注册邮箱验证链接";
        String content = serverUrl+"/validationUserEmail/"+user_id;
        System.err.println("content = " + content);

        sendSimpleMail(user_email,subject,content);
    }


    /**
     * 发送简单文本的邮件方法
     * @param to
     * @param subject
     * @param content
     */
    @Override
    public void sendSimpleMail(String to,String subject,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }


    /**
     * 发送HTML邮件的方法
     * @param to
     * @param subjecr
     * @param content
     */
    @Override
    public void sendHtmlMail(String to ,String subjecr,String content){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setTo(to);
            helper.setFrom(from);
            helper.setSubject(subjecr);
            helper.setText(content,true);
            mailSender.send(message);
            logger.info("发送静态邮件成功");
        } catch (MessagingException e) {
            logger.error("发送静态邮件失败：",e);
        }

    }

    @Override
    public void sendMail(String to, String subjecr, String content) {
//        sendHtmlMail(to ,subjecr,content);
        sendSimpleMail(to ,subjecr,content);
    }

}
